package com.tuzhi.filestore.controller;

import com.tuzhi.base.web.util.TZFileUtils;
import com.tuzhi.filestore.config.FileStoreConfig;
import com.tuzhi.filestore.http.FileStoreOtherApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * 此接口是给前端页面调用 ，可能会与 FileModelController 接口有所有重复
 * 因为 FileModelController 是己给欧总解释器用的，己稳定，所以重新写前端的
 * 后面再整合
 */
@Api(description = "前端页面模型展示")
@RestController
@RequestMapping("/api/model")
@Slf4j
public class WebModelController {
    @Autowired
    FileStoreConfig fileStoreConfig;
    @Resource
    FileStoreOtherApi fileStoreOtherApi;

    /**
     * 文件下载
     *
     * @param modelId  id
     * @param request  请求
     * @param response 响应
     */
    @ApiOperation(value = "下载文件 TuoDocument")
    @GetMapping(value = "/getDoc/{modelId}")
    public void downFile(@PathVariable("modelId") Long modelId, HttpServletRequest request, HttpServletResponse response
            , @RequestHeader(required = false) String redirect) {
        //log.info("前端调用接口 downFile");
        String filePath = Paths.get(this.fileStoreConfig.getSavePath(), "tuovisual", String.format("%s.TuoDocument", modelId)).toString();
        //log.info("前端调用接口 downFile:{}",filePath);
        boolean isRedirect = fileStoreConfig.redirectDownFile(redirect);//是否可以跳转到其他服务器下载
        boolean result = TZFileUtils.downFile(filePath, String.format("%s.TuoDocument", modelId), request, response, isRedirect);
        if (!result) {
            log.info("下载文件 TuoDocument，modelId={}，跳转下载", modelId);
            InputStream inputStream = fileStoreOtherApi.download(modelId);
            TZFileUtils.downFile(filePath, String.format("%s.TuoDocument", modelId), request, response, inputStream);
        }
    }

    @ApiOperation(value = "下载文件 tuovisual ")
    @GetMapping(value = "/uploads/tuovisual/{fileName}")
    public void downTuovisual(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response
            , @RequestHeader(required = false) String redirect) {
        String filePath = Paths.get(this.fileStoreConfig.getSavePath(), "tuovisual", fileName).toString();
        //log.info("前端调用接口 downFile:{}",filePath);
        boolean isRedirect = fileStoreConfig.redirectDownFile(redirect);//是否可以跳转到其他服务器下载
        boolean result = TZFileUtils.downFile(filePath, fileName, request, response, isRedirect);
        if (!result) {
            log.info("下载文件 tuovisual,fileName={}，跳转下载", fileName);
            InputStream inputStream = fileStoreOtherApi.tuovisual(fileName);
            TZFileUtils.downFile(filePath, fileName, request, response, inputStream);
        }
    }

}

